package com.wchat.serviceimpl;

import com.wchat.dataobject.ProductInfo;
import com.wchat.dto.CartDto;
import com.wchat.dto.OrderDto;
import com.wchat.enums.ProductStatusEnum;
import com.wchat.enums.ResultEnum;
import com.wchat.exceptions.SellException;
import com.wchat.repository.ProductInfoRepository;
import com.wchat.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.List;

/**
 * Created by yangtianrui on 17/8/10.
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductInfoRepository service;
    @Override
    public ProductInfo findOne(String productId) {
        return service.findOne(productId);
    }

    @Override
    public List<ProductInfo> findUpAll() {
        return service.findByProductStatus(ProductStatusEnum.ONLINE.getCode());
    }

    @Override
    public Page<ProductInfo> findAll(Pageable pageable) {
        return service.findAll(pageable);
    }

    @Override
    public ProductInfo save(ProductInfo productInfo) {
        return service.save(productInfo);
    }

    @Override
    @Transactional
    public void increseStock(List<CartDto> cartDtoList) {
        for(CartDto cartDto :cartDtoList)
        {
            ProductInfo productInfo = service.findOne(cartDto.getProductId());
            if(productInfo == null)
            {
                throw  new SellException(ResultEnum.PRODUCT_NOT_EXITS);
            }
            Integer result =productInfo.getProductStock() + cartDto.getProductQuantity();
            productInfo.setProductStock(result);
            service.save(productInfo);
        }


    }

    /**
     * 减库存
     * @param cartDtoList
     */
    @Override
    @Transactional
    public void decreseStock(List<CartDto> cartDtoList) {
        for(CartDto cartDto :cartDtoList)
        {
            ProductInfo productInfo = service.findOne(cartDto.getProductId());
            if(productInfo == null)
            {
                throw  new SellException(ResultEnum.PRODUCT_NOT_EXITS);
            }
            Integer result = productInfo.getProductStock() - cartDto.getProductQuantity();
            if(result < 0)
            {
                throw new SellException(ResultEnum.STOCK_SHORTAGE);
            }
            productInfo.setProductStock(result);

            service.save(productInfo);
        }
    }
}
